package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(0L))
                .map(menu -> {
                    menu.setChildren(getChildrens(menu, entities));
                    return menu;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        return level1Menus;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        return children;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removeCategoryByIds(List<Long> catIds) {
        baseMapper.deleteBatchIds(catIds);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        LinkedList<Long> path = new LinkedList<>();
        findCatelogPath(catelogId, path);
        return path.toArray(new Long[path.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
    @Override
    @Transactional
    @CacheEvict(value = "category", allEntries = true)
    public void updateCasCade(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = "category", key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        long l = System.currentTimeMillis();
        List<CategoryEntity> result = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("消耗的时间：" + (System.currentTimeMillis() - l));
        return result;
    }

    @Override
    @Cacheable(value = "category", key = "#root.methodName")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        return getCatalogJsonFromDB();
    }

    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithRedisLock() {
        String s = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(s)) {
            String uuid = UUID.randomUUID().toString();
            Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "uuid", 30, TimeUnit.SECONDS);
            if (lock) {
                Map<String, List<Catalog2Vo>> fromDB = null;
                try {
                    fromDB = getCatalogJsonFromDB();
                } finally {
                    String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                    Long lock1 = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList("lock"), uuid);
                }
                String catalogJson = JSON.toJSONString(fromDB);
                redisTemplate.opsForValue().set("catalogJson", catalogJson);

                return fromDB;
            } else {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    log.error("", e);
                } finally {
                    getCatalogJsonFromDBWithRedisLock();
                }
            }
        } else {
            log.error("读缓存！");
        }

        return JSON.parseObject(s, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
    }

    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithLocalLock() {
        String s = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(s)) {
            Map<String, List<Catalog2Vo>> fromDB;
            synchronized (this) {
                s = redisTemplate.opsForValue().get("catalogJson");
                if (StringUtils.isEmpty(s)) {
                    fromDB = getCatalogJsonFromDB();
                    String catalogJson = JSON.toJSONString(fromDB);
                    redisTemplate.opsForValue().set("catalogJson", catalogJson);
                    return fromDB;
                }
            }
        } else {
            log.error("读缓存！");
        }

        return JSON.parseObject(s, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
    }

    private Map<String, List<Catalog2Vo>> getCatalogJsonFromDB() {

        List<CategoryEntity> allCategorys = this.baseMapper.selectList(null);

        List<CategoryEntity> level1Categorys = getCategorysByPid(allCategorys, 0);
        Map<String, List<Catalog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categorys = getCategorysByPid(allCategorys, v.getCatId());
            List<Catalog2Vo> catalog2VoList = null;
            if (!CollectionUtils.isEmpty(categorys)) {
                catalog2VoList = categorys.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    List<CategoryEntity> l3Entitys = getCategorysByPid(allCategorys, l2.getCatId());
                    if (!CollectionUtils.isEmpty(l3Entitys)) {
                        List<Catalog2Vo.Catalog3Vo> l3Vos = l3Entitys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo l3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return l3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(l3Vos);
                    }

                    return catalog2Vo;
                }).collect(Collectors.toList());
            }

            return catalog2VoList;
        }));

        return map;
    }

    private List<CategoryEntity> getCategorysByPid(List<CategoryEntity> allCategorys, long pId) {
        return allCategorys.stream().filter(item -> item.getParentCid() == pId).collect(Collectors.toList());
    }

    private void findCatelogPath(Long catelogId, LinkedList<Long> path) {
        path.addFirst(catelogId);
        CategoryEntity category = getById(catelogId);
        if (category.getParentCid() != 0) {
            findCatelogPath(category.getParentCid(), path);
        }
    }
}